import plugin from '../../../lib/plugins/plugin.js'
import path from 'path'
import { fileURLToPath } from 'url'
import fs from 'fs'

const __filename = fileURLToPath(import.meta.url)
const __dirname = path.dirname(__filename)

export default class xiyangHelp extends plugin {
  constructor() {
    super({
      cron: void 0,
      name: "夕阳帮助",
      dsc: "图片版功能菜单",
      event: "message",
      priority: 500,
      rule: [
        {
          reg: "^#?夕阳帮助$",
          fnc: "fixedImageHelp"
        }
      ]
    })

    // 资源路径配置
    this.resourceDir = path.resolve(__dirname, '../resources')
    this.backgroundPath = path.resolve(this.resourceDir, 'images/背景图.png')
    this.outputDir = path.resolve(this.resourceDir, 'images/outputs')
    this.htmlTemplate = path.resolve(this.resourceDir, 'template/xiyang-help.html')

    // 自动初始化
    (async () => {
      try {
        await this.initFileSystem()
        console.log(`[${this.name}] 初始化完成`)
      } catch (err) {
        console.error(`[${this.name}] 初始化失败:`, err)
      }
    })()
  }

  async initFileSystem() {
    try {
      // 创建必要目录
      const requiredDirs = [
        this.outputDir,
        path.dirname(this.htmlTemplate)
      ]

      for (const dir of requiredDirs) {
        if (!fs.existsSync(dir)) {
          fs.mkdirSync(dir, { recursive: true })
          console.log(`[${this.name}] 创建目录: ${dir}`)
        }
      }

      // 生成默认背景图
      if (!fs.existsSync(this.backgroundPath)) {
        console.log(`[${this.name}] 生成默认背景图...`)
        await this.generateDefaultBackground()
      }

      // 生成HTML模板
      if (!fs.existsSync(this.htmlTemplate)) {
        fs.writeFileSync(this.htmlTemplate, this.generateHTML())
        console.log(`[${this.name}] 生成模板文件: ${this.htmlTemplate}`)
      }
    } catch (err) {
      console.error(`[${this.name}] 文件系统错误:`, err)
      throw err
    }
  }

  async generateDefaultBackground() {
    try {
      const { createCanvas } = await import('canvas')
      
      const canvas = createCanvas(1280, 720)
      const ctx = canvas.getContext('2d')

      // 渐变背景
      const gradient = ctx.createLinearGradient(0, 0, canvas.width, canvas.height)
      gradient.addColorStop(0, '#2c3e50')
      gradient.addColorStop(1, '#3498db')
      ctx.fillStyle = gradient
      ctx.fillRect(0, 0, canvas.width, canvas.height)

      // 标题文字
      ctx.fillStyle = 'rgba(255, 255, 255, 0.9)'
      ctx.font = 'bold 48px "Microsoft YaHei"'
      ctx.textAlign = 'center'
      ctx.textBaseline = 'middle'
      ctx.fillText('夕阳娱乐功能菜单', canvas.width/2, canvas.height/2)

      // 保存文件
      const out = fs.createWriteStream(this.backgroundPath)
      canvas.createPNGStream().pipe(out)
      await new Promise(resolve => out.on('finish', resolve))
    } catch (err) {
      console.error(`[${this.name}] 背景生成失败:`, err)
      throw err
    }
  }

  generateHTML() {
    return `<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>夕阳功能菜单</title>
  <style>
    :root {
      --main-color: #ff6b6b;
      --sub-color: #4ecdc4;
    }

    body {
      background: url('file://${path.resolve(this.backgroundPath)}') no-repeat center/cover;
      min-height: 100vh;
      margin: 0;
      padding: 20px;
      font-family: 'Microsoft YaHei', sans-serif;
    }

    /* 其余样式保持不变... */
  </style>
</head>
<body>
  <!-- HTML内容保持不变... -->
</body>
</html>`
  }

  async fixedImageHelp(e) {
    try {
      console.log(`[${this.name}] 收到帮助请求`)

      // 依赖检查
      if (!await this.checkDependencies()) {
        await this.reply([
          '❌ 需要以下依赖：',
          '1. Chromium浏览器',
          '2. 中文字体包',
          '3. 文件写入权限'
        ].join('\n'))
        return false
      }

      // 生成图片路径
      const outputPath = path.resolve(this.outputDir, `help-${Date.now()}.png`)

      // 调用渲染
      await this.e.render({
        tplFile: this.htmlTemplate,
        savePath: outputPath,
        width: 1200,
        height: 1800,
        renderOptions: {
          executablePath: '/usr/bin/chromium-browser',
          args: [
            '--no-sandbox',
            '--disable-setuid-sandbox',
            '--disable-dev-shm-usage'
          ]
        }
      })

      // 验证结果
      if (fs.existsSync(outputPath)) {
        await this.reply([segment.image(`file://${outputPath}`)])
        return true
      }
      throw new Error('渲染输出文件不存在')
    } catch (err) {
      console.error(`[${this.name}] 处理失败:`, err)
      await this.reply('⚠️ 功能菜单生成失败，请检查后台日志')
      return false
    }
  }

  async checkDependencies() {
    const checks = [
      { 
        name: 'Chromium浏览器',
        check: () => fs.existsSync('/usr/bin/chromium-browser')
      },
      {
        name: 'HTML模板',
        check: () => fs.existsSync(this.htmlTemplate)
      },
      {
        name: '写入权限',
        check: () => {
          try {
            fs.accessSync(this.outputDir, fs.constants.W_OK)
            return true
          } catch {
            return false
          }
        }
      }
    ]

    for (const { name, check } of checks) {
      if (!check()) {
        console.error(`[${this.name}] 依赖缺失: ${name}`)
        return false
      }
    }
    return true
  }
}
